//
//  LIUViewController.m
//  RxNet
//
//  Created by liuyu on 17/12/16.
//  Copyright (c) 2016 limit. All rights reserved.
//

#import "LIUViewController.h"
#import "LIURequestViewModel.h"
#import "LIUMovieCell.h"
#import "LIUMovie.h"
#import "LIUSubjects.h"

@interface LIUViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) LIURequestViewModel *requestVm;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *movies;
@end

@implementation LIUViewController

#pragma mark - lazy

- (LIURequestViewModel *)requestVm {
    if (!_requestVm) {
        _requestVm = [[LIURequestViewModel alloc] init];
    }
    return _requestVm;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds
                                                  style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
    }
    return _tableView;
}

- (NSArray *)movies {
    if (!_movies) {
        _movies = [[NSArray alloc] init];
    }
    return _movies;
}

#pragma mark - life cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupView];
    [self sendRequest];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - events

- (void)setupView {
    [self.view addSubview:self.tableView];
}

- (void)sendRequest {
    // 即将上映
    // https://api.douban.com/v2/movie/coming_soon
    @weakify(self)
    NSString *coming_soon = @"https://api.douban.com/v2/movie/coming_soon";
    [[self.requestVm.getCommand execute:coming_soon]
     subscribeNext:^(LIUMovie *x) {
         @strongify(self)
         self.movies = x.subjects;
         //        dispatch_queue_t queue = dispatch_get_main_queue();
         dispatch_sync(dispatch_get_main_queue(), ^{
             [_tableView reloadData];
         });
     }];
    // post 请求
    NSString *recommendVideo = @"http://lishengrong.ngrok.cc/hyzhiyin/av/recommendVideo";
    NSString *params = @"type=0&bigClassId=audio1";
    [[self.requestVm.postCommand execute:@[recommendVideo, params]] subscribeNext:^(id x) {
        NSLog(@"%@", x);
    }];
}

#pragma mark - Table view data source & delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.movies.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LIUMovieCell *cell = [LIUMovieCell movieWithTableView:tableView reuseIdentifier:NSStringFromClass([LIUMovieCell class])];
    //    cell.movie = self.movies[indexPath.row];
    LIUSubjects *sub = self.movies[indexPath.row];
    cell.textLabel.text = sub.title;
    return cell;
}

@end
